package alfred.proctice.com.recycleview;

import android.content.Context;
import android.content.res.Configuration;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;

import alfred.proctice.com.recycleviewother.HeaderAndFooterWrapper;

/**
 * Created by Alfred on 2018/3/12.
 */

public class RefreshRecycleView extends RecyclerView {
    private Context context;
    private View headerView,footerView;
    private float downY;
    private double moveScale = 0.3;
    private int maxHeight;
    private HeaderAndFooterWrapper wrapper;
    private AnimationDrawable topAnim,bottomAnim;
    private LinearLayoutManager layoutManager;
    private boolean TOP_ISRREADY_REFRESH = false;//是否具备刷新
    private boolean TOP_REFRESHING = false;//正在刷新
    private boolean BOTTOM_ISRREADY_LOAD = false;//是否具备加载更多
    private boolean BOTTOM_LOADING = false;//正在加载更多
    public onRefreshListener onRefreshListener;
    public onLoadMoreListener onLoadMoreListener;
    public RefreshRecycleView(Context context) {
        this(context,null);
    }

    public RefreshRecycleView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public RefreshRecycleView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        initHeaderView();
        initFooterView();
    }

    private void initHeaderView(){
        headerView = View.inflate(context,R.layout.item_topfresh,null);
        headerView.measure(0,0);
        maxHeight = headerView.getMeasuredHeight()-10;
        headerView.setPadding(0,-maxHeight,0,0);
        final int offset = computeVerticalScrollOffset();
        topAnim = (AnimationDrawable) headerView.findViewById(R.id.item_topfresh_img).getBackground();
        layoutManager = (LinearLayoutManager) getLayoutManager();
    }

    private void initFooterView(){
        footerView = View.inflate(context,R.layout.item_bottomload,null);
        footerView.measure(0,0);
        maxHeight = footerView.getMeasuredHeight()-10;
        footerView.setPadding(0,0,0,-maxHeight);
        final int offset = computeVerticalScrollOffset();
        bottomAnim = (AnimationDrawable) footerView.findViewById(R.id.item_bottomlod_img).getBackground();
        layoutManager = (LinearLayoutManager) getLayoutManager();
    }

    public void setAdapterWithHeaderView(Adapter adapter){
        wrapper = new HeaderAndFooterWrapper(adapter);
        wrapper.addHeaderView(headerView);
        setAdapter(wrapper);
    }

    public void setAdapterWithFooterView(Adapter adapter){
        wrapper = new HeaderAndFooterWrapper(adapter);
        wrapper.addFootView(footerView);
        setAdapter(wrapper);
    }

    public void setAdapterWithBoth(Adapter adapter){
        wrapper = new HeaderAndFooterWrapper(adapter);
        wrapper.addHeaderView(headerView);
        wrapper.addFootView(footerView);
        setAdapter(wrapper);
    }

    @Override
    public void onScrollStateChanged(int state) {
        super.onScrollStateChanged(state);
        if(state == RecyclerView.SCROLL_STATE_IDLE||state == RecyclerView.SCROLL_STATE_SETTLING){
            if(layoutManager instanceof LinearLayoutManager){
                Log.v("wrapper.getItemCount():",""+wrapper.getItemCount());
                if(((LinearLayoutManager) layoutManager).findLastVisibleItemPosition()==wrapper.getItemCount()-1){
                    startLoad();
                }
            }
        }
    }

    @Override
    public void onScrolled(int dx, int dy) {
        super.onScrolled(dx, dy);

    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
    }

    /*    @Override
    public boolean onTouchEvent(MotionEvent e) {
        switch (e.getAction()){
            case MotionEvent.ACTION_DOWN:
                downY = e.getRawY();
                Log.v("ScrollOffset按下：",computeVerticalScrollOffset()+"");
                break;
            case MotionEvent.ACTION_MOVE:
                int position = layoutManager.findFirstVisibleItemPosition();
                float relatY = downY - e.getRawY();
                if(relatY < 0&&isScrollToTop()&&!TOP_REFRESHING){
                    if(Math.abs(relatY)*moveScale >= maxHeight){
                        TOP_ISRREADY_REFRESH = true;
                    }else{
                        TOP_ISRREADY_REFRESH = false;
                    }
                    headerView.setPadding(0,(int)(Math.abs(relatY)*moveScale)-maxHeight,0,0);
                    Log.v("ScrollOffset滑动：",computeVerticalScrollOffset()+"");
                }
                if(relatY>0&&isScrollToBottom()&&!BOTTOM_LOADING){
                    Log.v("ScrollToBottom底部：","到达底部");
                    if(Math.abs(relatY)*moveScale >= maxHeight){
                        BOTTOM_ISRREADY_LOAD = true;
                    }else{
                        BOTTOM_ISRREADY_LOAD = false;
                    }
                    footerView.setPadding(0,0,0,(int)(Math.abs(relatY)*moveScale)-maxHeight);
                }
                break;
            case MotionEvent.ACTION_UP:
                if(!TOP_REFRESHING) {//刷新时不能做任何滑动改动
                    if (!TOP_ISRREADY_REFRESH) {
                        resetHeaderView();
                    } else {
                        startRefresh();
                    }
                    TOP_ISRREADY_REFRESH = false;
                }
                if(!BOTTOM_LOADING) {//刷新时不能做任何滑动改动
                    if (!BOTTOM_ISRREADY_LOAD) {
                        resetFooterView();
                    } else {
                        startLoad();
                    }
                    BOTTOM_ISRREADY_LOAD = false;
                }

                break;
        }
        return super.onTouchEvent(e);
    }*/

    private void resetHeaderView(){
        headerView.setPadding(0,-maxHeight,0,0);
        topAnim.stop();
    }

    private void startRefresh(){
        headerView.setPadding(0, 0, 0, 0);
        topAnim.start();
        TOP_REFRESHING = true;
        onRefreshListener.rereshing();//开始刷新
    }

    private void resetFooterView(){
        footerView.setPadding(0,0,0,-maxHeight);
        bottomAnim.stop();
    }

    private void startLoad(){
        footerView.setPadding(0, 0, 0, 0);
        bottomAnim.start();
        BOTTOM_LOADING = true;
        onLoadMoreListener.loading();//开始刷新
    }

    /**
     * 结束加载/刷新动画
     */
    public void completeRefresh(){
        if(TOP_REFRESHING) {
            TOP_REFRESHING = false;
            resetHeaderView();
        }
        if(BOTTOM_LOADING){
            BOTTOM_LOADING = false;
            resetFooterView();
        }
    }


    private boolean isScrollToTop(){
        final int offset = computeVerticalScrollOffset();
        return offset == 0;
    }

    private boolean isScrollToBottom(){
        final int offset = computeVerticalScrollOffset();
        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
        return offset > 0 && offset >= range - 1;
    }

    public interface onRefreshListener{
        void rereshing();
    }

    public void setOnRefreshListener(RefreshRecycleView.onRefreshListener onRefreshListener) {
        this.onRefreshListener = onRefreshListener;
    }

    public interface onLoadMoreListener{
        void loading();
    }

    public void setOnLoadMoreListener(RefreshRecycleView.onLoadMoreListener onLoadMoreListener) {
        this.onLoadMoreListener = onLoadMoreListener;
    }
}
